//定义一个聊天框
import { useState, useEffect } from "react"
import store from "./Store"

//引入action

import * as chatActions from "./Store/Actions/ChatAction"

const ChatBox = (props) => {
    let [chatInfo, setChatInfo] = useState(store.getState())
    let [val, setVal] = useState("") //控制input输入框的值
    //使用useEffect订阅state的变化

    useEffect(() => {
        store.subscribe(() => {
            setChatInfo(store.getState())
        })
    }, [])

    let handleInputChange = (e) => { //input输入框组件受控的方法
        setVal(e.target.value)
    }

    let handleSend = () => { //将结果发送给redux,变更状态,更新视图
        //变更stor中的状态,只能通过dispatch派发action来变更
        //并且要传递input更新之后的value值
        store.dispatch(chatActions.addChatLog(val))
    }

    //改变用户名

    let handleChangeName = () => {
        store.dispatch(chatActions.changeUsername("李雷"))
    }

    //更新用户

    let handleChangeStatus = () => {
        store.dispatch(chatActions.changeStatus)
    }

    //将store中的属性进行解构
    let { username, statusMsg, chatLog = [] } = chatInfo;
    //当statusMsg的结果是false,那么返回null
    if (statusMsg) {
        return (
            <fieldset>
                <legend>聊天室</legend>
                <button onClick={handleChangeStatus}>点击退出</button>
                <h1>用户名:{username}</h1>
                <button onClick={handleChangeName}>点击改变用户名</button>
                <fieldset>
                    <legend>聊天记录</legend>
                    <input type="text" value={val} onChange={handleInputChange} />
                    <button onClick={handleSend}>发送</button>
                    <ul>
                        {
                            chatLog.map((log, i) => {
                                return <li key={i}>{log}</li>
                            })
                        }
                    </ul>
                </fieldset>
            </fieldset>
        )
    } else {
        return <button onClick={handleChangeStatus}>点击登入</button>
    }
}

export default ChatBox